from django.shortcuts import render, redirect, reverse

from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.forms import UserCreationForm
# Create your views here.


def logout_view(request):
    """注销用户"""
    logout(request)
    return redirect(reverse("app01:index"))


def register_view(request):
    """注册"""
    print(request.method)
    if request.method != "POST":
        form = UserCreationForm()
        return render(request, "users/register.html", {"form": form})
    else:
        form = UserCreationForm(data=request.POST)

        if form.is_valid():
            new_user = form.save()
            # 让用户自动登录，再重定向到主页
            authenticated_user = authenticate(username=new_user.username,
                                              password=request.POST['password1'])
            login(request, authenticated_user)
            return redirect(reverse("app01:index"))
        else:
            return render(request, "users/register.html", {'form': form})
